<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>DynamicClick</title>
    
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
</head>
<body>

<table>
    <thead>
    
    </thead>
    <tbody id="tableBody">
    
    <tr>
        <td>
            1.
        </td>
        <td>
            2.
        </td>
        <td>
            3.
        </td>
    </tr>
    
    <tr>
        <td>
            4.
        </td>
        <td>
            5.
        </td>
        <td>
            6.
        </td>
    </tr>
    
    <tr>
        <td>
            7.
        </td>
        <td>
            8.
        </td>
        <td>
            9.
        </td>
    </tr>
    
    </tbody>
    <tfoot>
    
    </tfoot>

</table>

<script type="text/javascript">
    
    function log(index) {
        console.log(index)
        var people = peoples[index];
        console.info(people)
    }
    
    var peoples = [{name: '朱元璋', age: 18, sex: '男'}, {name: '李思思', age: 19, sex: '女'}, {name: '朱崇巴', age: 20, sex: '男'}]
    
    var tableBodyElement = document.getElementById('tableBody');
    
    var peoplesArrayLength = peoples.length;
    
    peoples.forEach(function (item) {
        console.log(item.name, item.age, item.sex)
    })
    
    var str = ''
    
    for (var i = 0; i < peoplesArrayLength; i++) {
        
        str += '<tr>';
        var people = peoples[i];
        console.log('people = ' + people);
        var trElement = document.createElement('tr');
        var nameElement = document.createElement('td');
        var ageElement = document.createElement('td');
        var sexElement = document.createElement('td');
        
        str += '<td onclick=log(' + i + ')>' + people.name + '</td>'
        str += '<td onclick=log(' + i + ')>' + people.age + '</td>'
        str += '<td onclick=log(' + i + ')>' + people.sex + '</td>'
        
        trElement.appendChild(nameElement);
        trElement.appendChild(ageElement);
        trElement.appendChild(sexElement);
        
        nameElement.innerHTML = people.name;
        ageElement.innerHTML = people.age;
        sexElement.innerHTML = people.sex;
        
        nameElement.setAttributeNode(generateTDStyleNode());
        ageElement.setAttributeNode(generateTDStyleNode());
        sexElement.setAttributeNode(generateTDStyleNode());
        
        
        tableBodyElement.appendChild(trElement);
        str += '</tr>'
    }
    var tempStr = tableBodyElement.innerHTML;
    tableBodyElement.innerHTML = tempStr + str;
    
    function generateTDStyleNode() {
        var tdStyleAttribute = document.createAttribute('style');
        tdStyleAttribute.value = 'width:100px; background-color:#ff2841; color:white; font-size:18px; text-align:center';
        return tdStyleAttribute;
    }

</script>

</body>
</html>
